package com.now.controller;

import com.now.entity.User;
import com.now.service.IUserService;
import com.now.utils.AesUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;

@Controller
public class LoginController {

    @Resource
    IUserService userService;

    /**
     * 首页
     * @return
     */
    @GetMapping("/")
    public String index() {
        return "index";
    }

    /**
     * 首页
     * @return
     */
    @GetMapping("/toIndex")
    public String toIndex(@RequestParam String username, Model model) {
        if (!"".equals(username) && null != username){
            model.addAttribute("username", username);
            return "index";
        }
        return "index";
    }

    /**
     * 跳转登录页
     * @return
     */
    @GetMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    /**
     * 跳转注册页
     * @return
     */
    @GetMapping("/toRegister")
    public String toRegister() {
        return "register";
    }

    /**
     * 登录
     * @param username
     * @param password
     * @param model
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password, Model model) {
        if ("".equals(username)) {
            model.addAttribute("error", "");
            return "login";
        }
        User user = userService.queryByUsername(username);
        if(null == user){
            model.addAttribute("error", "用户名不存在！");
            return "login";
        }
        // 解析数据库中的密码
        String newPassword = AesUtil.decrypt(user.getPassword());
        if (username.equals(user.getUsername()) && password.equals(newPassword)){
            model.addAttribute("username", username);
            return "index";
        }else {
            model.addAttribute("error", "用户名或密码错误！");
        }
        return "login";
    }

    /**
     * 注册
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    public String register(@RequestParam String username, @RequestParam String password, Model model) {
        if("".equals(username)){
            model.addAttribute("error", "用户名不能为空！");
            return "register";
        }
        if("".equals(password)){
            model.addAttribute("error", "密码不能为空！");
            return "register";
        }
        boolean result = userService.save(username,password);
        if(!result){
            model.addAttribute("error", "注册失败！");
            return "register";
        }
        return "login";
    }
}
